package com.xgzit.xgzmall.seckill.controller;

import com.xgzit.common.utils.R;
import com.xgzit.common.vo.MemberEntityVo;
import com.xgzit.xgzmall.seckill.dto.SeckillSkuRedisDto;
import com.xgzit.xgzmall.seckill.interceptor.LoginUserInterceptor;
import com.xgzit.xgzmall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author xgz
 * @Date 2021-07-14 22:13
 */
@Slf4j
@Controller
public class SeckillController {

    @Autowired
    SeckillService seckillService;

    /**
     * 返回当前时间可以参与的秒杀商品信息
     **/
    @ResponseBody
    @GetMapping("/currentSeckillSkus")
    public R getCurrentSeckillSkus() {
        List<SeckillSkuRedisDto> dtoList = seckillService.getCurrentSeckillSkus();
        log.info(dtoList.toString());
        return R.ok().setData(dtoList);
    }

    @ResponseBody
    @GetMapping("/sku/seckill/{skuId}")
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        /*try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        SeckillSkuRedisDto dto = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(dto);
    }

    // killId=2_8&num=1&key=56d1dfd6058d4a708e05a057119562ff
    @GetMapping("/kill")
    public String secKill(@RequestParam("killId") String killId,
                          @RequestParam("num") Integer num,
                          @RequestParam("key") String key,
                          Model model) {
        // 1、判断是否登录
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        if (Objects.isNull(memberEntityVo)) {
            // 去 登录
        }
        String orderSn = seckillService.kill(killId, num, key);
        model.addAttribute("orderSn", orderSn);
        return "success";
    }
}
